﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;

namespace Nirvana
{
    /// <summary>
    /// UI跟随3D对象坐标在屏幕界面移动
    /// </summary>
    [RequireComponent(typeof(RectTransform))]
    [AddComponentMenu("Nirvana/UI/Control/UI Follow Target")]
    public class UIFollowTarget : MonoBehaviour
    {
        [SerializeField]
        private Transform target;
        [SerializeField]
        private Camera gameCamera;
        [SerializeField]
        private Canvas canvas;
        private RectTransform _recttransform;

        // Use this for initialization
        void Awake()
        {
            this._recttransform = GetComponent<RectTransform>();
            if (gameCamera == null) gameCamera = Camera.main;
        }

        // Update is called once per frame
        void FixedUpdate()
        {
            if (this.gameCamera == null)
            {
                this.gameCamera = Camera.main;
            }
            this.UpdatePosition();
        }

        private void UpdatePosition()
        {
            if (target == null || canvas == null || gameCamera == null || _recttransform == null) return;
            Vector3 position = CalculateScreenPosition(this.target.position, this.gameCamera, this.canvas, this._recttransform);
            transform.position = position;
        }

        public  Vector3 CalculateScreenPosition(Vector3 position, Camera camera, Canvas canvas, RectTransform transform)
        {
            Assert.IsNotNull<Camera>(camera);
            Assert.IsNotNull<Canvas>(canvas);
            Assert.IsNotNull<RectTransform>(transform);
            Vector3 vector = camera.WorldToScreenPoint(position);
            Vector3 zero = Vector3.zero;
            switch (canvas.renderMode)
            {
                case 0:
                    RectTransformUtility.ScreenPointToWorldPointInRectangle(transform, vector, null, out zero);
                    break;
                case RenderMode.ScreenSpaceCamera:
                case RenderMode.WorldSpace:
                    RectTransformUtility.ScreenPointToWorldPointInRectangle(transform, vector, canvas.worldCamera, out zero);
                    break;
            }
            return zero;
        }
    }
}

